package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired(required = false)
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //1.生成验证码，发送短信
        String code = "1234";

       /* session.setAttribute(user.getPhone(),code);
        //2. 把验证码存储到session中
        session.setAttribute(user.getPhone(),code);*/

       redisTemplate.opsForValue().set(user.getPhone(),code,1, TimeUnit.MINUTES);//实际中一般有效时间是5分钟，但是上课为了快速演示效果，所以写了1分钟
        log.info("本次验证码："+code);
        return R.success("发送成功");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String,String> param,HttpSession session){
        //1.从map集合中取出用户输入的手机号与验证码
        String  phone = param.get("phone");
        String  inputCode = param.get("code");

       /* //2. 从session中获取系统的验证码
        String verifyCode = (String) session.getAttribute(phone);*/

       //从Redis中获取验证码
        String verifyCode = (String) redisTemplate.opsForValue().get(phone);

        //3. 把三个数据交给service
        User user = userService.login(phone,inputCode,verifyCode);
        if (user!=null){
            //登录成功，删除验证
            redisTemplate.delete(phone);
            //登录成功，把数据存储到session
            session.setAttribute("user",user.getId());
        }else {
            return R.error("登录失败");
        }
        return R.success(user);
    }
    @PostMapping("/loginout")
    public R<String> loginout(HttpSession session){
        session.invalidate();
        return R.success("退出成功");
    }
}
